//
//  GKDetailViewController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2019/9/5.
//  Copyright © 2019 wangws1990. All rights reserved.
//

import UIKit

class GKDetailViewController: BaseConnectionController {
    var model:GKBookDetailModel!
    class func vcWithBookId(bookId:String)->UIViewController{
        let vc :GKDetailViewController = GKDetailViewController.init();
        vc.bookId = bookId;
        return vc;
    }
    var height: CGFloat = 0;
    lazy var tabView: GKDetailTabView = {
        let tab :GKDetailTabView = GKDetailTabView.instanceView() ;
        tab.favBtn.addTarget(self, action:#selector(favAction(sender:)), for: .touchUpInside)
        tab.readBtn.addTarget(self, action: #selector(readAction), for: .touchUpInside);
        return tab;
    }()
    lazy var listData: [GKBookModel] = {
        return []
    }()
    lazy var backBtn: UIButton = {
        var backBtn = UIButton.init(type: .custom);
        backBtn.setImage(UIImage.init(named:"icon_detail_back"), for: .normal);
        backBtn.addTarget(self, action: #selector(goBackAction), for: .touchUpInside);
        return backBtn;
    }()
    var bookId:String! = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        loadUI();
    }
    override func viewDidAppear(_ animated: Bool) {
        super .viewDidAppear(animated)
        GKBookCaseDataQueue.getBookModel(bookId: self.bookId) { (model) in
            let bookId :String = model.bookId ?? "";
            self.tabView.favBtn.isSelected = !bookId.isEmpty;
            
        }
    }
    func loadUI(){
        self.fd_prefersNavigationBarHidden = true;
        self.collectionView.register(UINib.init(nibName: "GKDetailTopView", bundle: nil), forSupplementaryViewOfKind: "UICollectionElementKindSectionHeader", withReuseIdentifier: NSStringFromClass(GKDetailTopView.classForCoder()))
        if #available(iOS 11.0, *) {
            self.collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        self.view.addSubview(self.tabView);
        self.tabView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview();
            make.height.equalTo(49)
            make.bottom.equalToSuperview().offset(-TAB_BAR_ADDING);
        }
        self.collectionView.snp_remakeConstraints { (make) in
            make.top.left.right.equalToSuperview();
            make.bottom.equalTo(self.tabView.snp_top);
        }
        self.setupEmpty(scrollView: self.collectionView);
        self.setupRefresh(scrollView: self.collectionView, options: .Default);
        self.view.addSubview(self.backBtn);
        self.backBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15);
            make.width.height.equalTo(34);
            make.top.equalToSuperview().offset((STATUS_BAR_HIGHT)+5)
        }
    }
    @objc func readAction(){
        let dic : NSDictionary = self.model.toJSON()! as NSDictionary;
        let model :GKBookModel = GKBookModel.deserialize(from: dic)!
        GKJump.jumpToNovel(bookModel:model);
    }
    @objc func favAction(sender:UIButton) {
        if sender.isSelected == false {
            GKBookCaseDataQueue.insertBookModel(bookDetail: self.model) { (success) in
                if success{
                    self.tabView.favBtn.isSelected = true;
                    MBProgressHUD.showMessage("收藏成功");
                }
            }
        }else{
            ATAlertView.showAlertView(title: "是否取消收藏？", message:"", normals:["取消"], hights:["确定"]) { (title, index) in
                if index > 0{
                    GKBookCaseDataQueue.deleteBookModel(bookId: self.bookId, sucesss: { (success) in
                        if success{
                            MBProgressHUD.showMessage("取消收藏成功");
                            self.tabView.favBtn.isSelected = false;
                        }
                    })
                }
            }
        }
    }
    @objc func goBackAction(){
        self.goBack();
    }
    override func refreshData(page: Int) {
        let group :DispatchGroup = DispatchGroup.init();
        group.enter();
        group.enter();
        GKClassifyNetManager.bookDetail(bookId: self.bookId, sucesss: { (object) in
            if object is NSDictionary{
                let dic : NSDictionary = object as! NSDictionary;
                let model : GKBookDetailModel = GKBookDetailModel.deserialize(from: dic)!;
                self.model = model;
                self.height = GKDetailTopView.getHeight(model: self.model);
            }
            group.leave();
        }) { (error) in
            group.leave();
        }
        GKClassifyNetManager.bookCommend(bookId: self.bookId, sucesss: { (object) in
            if object is NSDictionary{
                if page == 1{
                    self.listData.removeAll();
                }
                let list :NSArray = object["books"] as! NSArray;
                for obj in list{
                    let model : GKBookModel = GKBookModel.deserialize(from: (obj as! NSDictionary))!
                    self.listData.append(model);
                }
            }
            group.leave();
        }) { (error) in
            group.leave();
        };
        group.notify(queue: DispatchQueue.main) {
            if self.listData.count == 0 && self.model == nil{
                self.endRefreshFailure();
            }else{
                self.collectionView.reloadData();
                self.endRefresh(more: false);
            }
        };
    }
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1;
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.listData.count;
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 15;
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 15;
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15);
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: SCREEN_WIDTH, height:self.height);
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let view :GKDetailTopView! = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: NSStringFromClass(GKDetailTopView.classForCoder()), for: indexPath) as! GKDetailTopView);
        view.model = self.model;
        return view;
    }
    
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (SCREEN_WIDTH - 60)/3.0;
        let height = width * 1.35 + 50;
        return CGSize.init(width: width, height: height);
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell :GKBookCell = GKBookCell.cellForCollectionView(collectionView: collectionView, indexPath: indexPath)
        cell.model = self.listData[indexPath.row] ;
        return cell;
    }
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model:GKBookModel = self.listData[indexPath.row] ;
        GKJump.jumpToDetail(bookId: model.bookId);
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent;
    }
}
